package com.pk.platform.util;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.pk.platform.domain.privilege.User;
import com.pk.platform.util.filter.SystemContext;

public class XmlUtil {

	private static Logger log = Logger.getLogger(XmlUtil.class);
	
	private Document xmlDoc = null;
	
	public XmlUtil(String xml)
	{
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version='1.0' encoding='UTF-8'?>").append(xml);
		try
		{
			xmlDoc = DocumentHelper.parseText(sb.toString());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Element getOneElement(String path)
	{
		List<Element> list = this.getElements(path);
		if(list.size() > 0)
		{
			return list.get(0);
		}
		return null;
	}
	
	public List<Element> getElements(String path)
	{
		List<Element> list = xmlDoc.selectNodes(path);
		return list;
	}
	
	public static String privilegeFilter(String menu)
	{
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version='1.0' encoding='UTF-8'?><lis>").append(menu).append("</lis>");
		User user = SystemContext.getUser();
		Document document = null;
		try
		{
			document = DocumentHelper.parseText(sb.toString());
			List<Element> list = document.selectNodes("//li");
			Map<String, String> privilege = user.getPrivilege();
			for(Element ele : list)
			{
				String idValue = ele.attribute("code").getValue();
				if(privilege.get(idValue) == null)
				{
					ele.detach(); //删除节点
				}
			}
		}
		catch (Exception e) {
			log.error("解释xml错误", e);
		}
		return document.asXML();
	}
	
	
	
}
